package com.smartad.ApplicationServer;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.StringTokenizer;

import com.smartad.Web.HttpRequestHandler;

public class HttpWorker extends Thread {
	private Socket _client;

	public HttpWorker(Socket ClientConn) {
		_client = ClientConn;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void run() {
		DataInputStream din = null;
		BufferedOutputStream out = null;
		try {
			din = new DataInputStream(_client.getInputStream());
			out = new BufferedOutputStream(_client.getOutputStream());

			String request = "";
			String s;
			while ((s = din.readLine()) != null) {
				if (s.isEmpty()) {
					break;
				}
				request += s + "\r\n";
			}

			com.smartad.common.Log.d(request);
			
			StringTokenizer st = new StringTokenizer(request);
			if (!st.hasMoreTokens())
				return;

			String header = st.nextToken();

			if (header.equals("GET")) {
				String fileName = st.nextToken();

				new HttpRequestHandler(fileName, out).doGet();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

			try {
				if (din != null) {
					din.close();
					din = null;
				}
				if (out != null) {
					out.close();
					out = null;
				}
				_client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
